package com.springboot.test.controller;

import com.springboot.test.domain.Result;
import com.springboot.test.domain.User;
import com.springboot.test.exception.WebException;
import com.springboot.test.repository.UserRepository;
import com.springboot.test.service.UserService;
import com.springboot.test.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Kang on 2017/8/12.
 */
@RestController
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserService userService;

    @GetMapping(value = "/getUsers")
    public List<User> getUsers() {
        return userRepository.findAll();
    }

    @PostMapping(value = "/addUser")
    public Result addUser(@Valid User user, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultUtil.error(1, bindingResult.getFieldError().getDefaultMessage());
        }

        return ResultUtil.success(userRepository.save(user));
    }

    @GetMapping(value = "/queryByName")
    public List<User> queryByName(@RequestParam(value = "name") String name) {
        return userRepository.findByNameLike("%" + name + "%");
    }

    @GetMapping(value = "/queryAgeById/{id}")
    public void queryById(@PathVariable(value = "id") Integer id) throws WebException {
        userService.queryAgeById(id);
    }

    @RequestMapping("/hi")
    public ModelAndView index(){
        ModelAndView modelAndView = new ModelAndView("/hi");
        List<User> userList = userRepository.findAll();
        modelAndView.addObject("userList", userList);
        modelAndView.addObject("name", "乔康");
        return modelAndView;
    }

    @RequestMapping("/hello/{name}")
    public ModelAndView hello(@PathVariable("name") String name) {
        ModelAndView modelAndView = new ModelAndView("/hello");
        modelAndView.addObject("name", name);
        return modelAndView;
    }

}
